import {get} from '~/plugins/axios';

const dictionary = {
  custom: {
    scale: 'company_scale',
    trades: 'trade',
    type: 'company_type',
  },
  user: {
    type: 'user_type', // 用户类型
  },
  menu: {
    menuType: 'menu_type', // 菜单类型
    openTarget: 'open_type', // 新页面打开的位置
  },
  datas: {
    dType: 'datas_type', // 菜单类型
  },
};

function autoDictionAryState (dictionary) {
  let step = {};
  for (let index in dictionary) {
    if (dictionary.hasOwnProperty(index)) {
      step[index] = false;
    }
  }
  return step;
}

function autoDictionAryMutations (state) {
  let step = {};
  for (let index in state) {
    if (state.hasOwnProperty(index)) {
      step['SET_' + index] = function (state) {
        state[index] = true;
      };
      step['DEL_' + index] = function (state) {
        state[index] = false;
      };
    }
  }
  return step;
}

function autoDictionAryActions (state, dictionary) {
  let step = {};
  for (let index in state) {
    if (state.hasOwnProperty(index)) {
      step['USE_' + index] = async function ({ state, commit }) {
        if (!state[index]) {
          try {
            await (() => {
              let i = 0;
              for (let key in dictionary[index]) {
                if (!dictionary[index].hasOwnProperty(key)) return;
                i++;
              }
              return new Promise(function (resolve, reject) {
                for (let key in dictionary[index]) {
                  if (dictionary[index].hasOwnProperty(key)) {
                    (async () => {
                      commit(index.toUpperCase() + '/SET_' + key, await get('/dictionary/?type=' + (dictionary[index][key] || key)), { root: true });
                      if (--i === 0) {
                        resolve();
                      }
                    })();
                  }
                }
              });
            })();
            commit('SET_' + index); // 标识已经加载过
          } catch (err) {
            commit('DEL_' + index); // 标识加载过程出错，需要下次页面重新加载。
            console.log(err);
          }
        }
      };
    }
  }
  return step;
}

export const state = () => (autoDictionAryState(dictionary));
export const mutations = autoDictionAryMutations(state());
export const actions = autoDictionAryActions(state(), dictionary);
